package com.demo.villageresidence.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.villageresidence.dto.AdminDTO;
import com.demo.villageresidence.dto.PasswordDTO;
import com.demo.villageresidence.dto.Result;
import com.demo.villageresidence.dto.UserDTO;
import com.demo.villageresidence.pojo.Admin;
import com.demo.villageresidence.pojo.User;
import com.demo.villageresidence.service.RemarkService;
import com.demo.villageresidence.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Autowired
    private RemarkService remarkService;

    @GetMapping("getAllUser")
    public Result getAllUser() {
        List<User> userList = userService.query().eq("is_delete", 0).list();
        return Result.ok(userList);
    }

    // 判断输入的账号（手机号）是否已经存在
    @GetMapping("phoneIsExist/{userPhone}")
    public Result phoneIsExist(@PathVariable("userPhone") String userPhone) {
        if (userService.query().eq("user_phone", userPhone).one() != null) {
            return Result.fail("该手机号已经注册");
        }
        return Result.ok("该手机号可以注册");
    }

    @GetMapping("getUserPage")
    public Result getAdminPage(@RequestParam(value = "current", defaultValue = "1") Integer current,
                               @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<User> page = userService.query().page(new Page<>(current, pageSize));
        List<User> records = page.getRecords();

        long total = page.getTotal();

        return Result.ok(records, total);

    }

    @DeleteMapping("deleteUserById/{id}")
    public Result deleteUserById(@PathVariable("id") Integer id) {

        if (userService.removeById(id) != true){
            return Result.fail("删除失败");
        }
        return Result.ok("删除成功");
    }

    @PostMapping("login")
    public Map<String,Object> login(@RequestBody UserDTO userDTO) {
        // 实现登录功能
        return userService.login(userDTO);
    }

    /*
    *  用户注册
    */
    @PostMapping("register")
    public Result register(@RequestBody User user) {
        return userService.register(user);
    }

    @GetMapping("getUserById/{id}")
    public Result getUserById(@PathVariable("id") Integer id) {
        User user = userService.getById(id);
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        userDTO.setUserPassword(null);
        userDTO.setUserAvatar(user.getUserAvatar());
        return Result.ok(userDTO);
    }

    @PutMapping("updateUserById")
    public Result updateUserById(@RequestParam("id") Integer id, @RequestParam("url") String url) {

        boolean update = userService.update().eq("user_id", id).set("user_avatar", url).update();
        if (update != true){
            return Result.fail("更新失败");
        }else {

            return Result.ok("更新成功");
        }
    }

    @GetMapping("getRealUserById/{id}")
    public Result getRealUserById(@PathVariable("id") Integer id) {
        User user = userService.getById(id);
        user.setUserPassword(null);
        return Result.ok(user);
    }

    @PutMapping("updatePassword")
    public Result updatePassword(@RequestBody PasswordDTO passwordDTO) {
        Integer userId = passwordDTO.getUserId();
        User user = userService.query().eq("user_id", userId).one();
        // 判断原密码是否正确
        if (!BCrypt.checkpw(passwordDTO.getOldPassword(),user.getUserPassword())){
            return Result.fail("原密码错误");
        }
        // 加密新密码
        // 对密码进行BCrypt加密
        String newPassword = BCrypt.hashpw(passwordDTO.getNewPassword());

        boolean update = userService.update().eq("user_id", userId).set("user_password", newPassword).update();
        if (update != true){
            return Result.fail("密码修改失败");
        }else {
            return Result.ok("密码修改成功");
        }
    }

    @PutMapping("updateUser")
    public Result updateUser(@RequestBody User user) {
        boolean update = userService.update()
                .eq("user_id", user.getUserId())
                .set("real_name", user.getRealName())
                .set("user_sex", user.getUserSex()).update();
        if (update != true){
            return Result.fail("更新失败");
        }else {
            remarkService.update().eq("remark_user_id",user.getUserId()).set("remark_target",user.getRealName()).update();
            return Result.ok("更新成功");
        }
    }

}
